package com.yupi.oj.service.impl;


import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.oj.common.ErrorCode;
import com.yupi.oj.constant.CommonConstant;
import com.yupi.oj.exception.BusinessException;
import com.yupi.oj.exception.ThrowUtils;
import com.yupi.oj.mapper.CommentMapper;
import com.yupi.oj.mapper.CommentThumbMapper;
import com.yupi.oj.model.dto.comment.CommentQueryRequest;
import com.yupi.oj.model.entity.Comment;
import com.yupi.oj.model.entity.CommentThumb;
import com.yupi.oj.model.entity.User;
import com.yupi.oj.model.vo.CommentVO;
import com.yupi.oj.service.CommentService;
import com.yupi.oj.service.UserService;
import com.yupi.oj.utils.SqlUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
* @author 兰飞宇
* @description 针对表【comment(评论)】的数据库操作Service实现
* @createDate 2024-12-14 16:07:21
*/
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment>
    implements CommentService {
    @Resource
    private UserService userService;

    @Resource
    private CommentThumbMapper commentThumbMapper;
    

    @Override
    public void validComment(Comment comment, boolean add) {
        if (comment == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        String content = comment.getContent();
        Long questionId = comment.getQuestionId();

        // 创建时，参数不能为空
        if (add) {
            ThrowUtils.throwIf(StringUtils.isAnyBlank(content,questionId.toString()), ErrorCode.PARAMS_ERROR);
        }
        // 有参数则校验
        if (StringUtils.isNotBlank(content) && content.length() > 1000) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标题过长");
        }
    }
    /**
     * 获取查询包装类
     *
     * @param commentQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Comment> getQueryWrapper(CommentQueryRequest commentQueryRequest) {
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        if (commentQueryRequest == null) {
            return queryWrapper;
        }
        queryWrapper.eq("questionId",commentQueryRequest.getQuestionId());
        //只分页查询出没有回复评论的评论
        queryWrapper.isNull("replyFatherId");
        String sortField = commentQueryRequest.getSortField();
        String sortOrder = commentQueryRequest.getSortOrder();
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }
    @Override
    public Page<CommentVO> getCommentVOPage(Page<Comment> commentPage, HttpServletRequest request) {
        List<Comment> commentList = commentPage.getRecords();
        Page<CommentVO> commentVOPage = new Page<>(commentPage.getCurrent(), commentPage.getSize(), commentPage.getTotal());
        if (CollUtil.isEmpty(commentList)) {
            return commentVOPage;
        }
        // 2. 已登录，获取用户点赞状态
        Map<Long, Boolean> commentIdHasThumbMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        Set<Long> commentIdSet = commentList.stream().map(Comment::getId).collect(Collectors.toSet());
        if (loginUser != null) {
            loginUser = userService.getLoginUser(request);
            // 获取点赞
            QueryWrapper<CommentThumb> commentThumbQueryWrapper = new QueryWrapper<>();
            commentThumbQueryWrapper.in("commentId", commentIdSet);
            commentThumbQueryWrapper.eq("userId", loginUser.getId());
            List<CommentThumb> commentThumbList = commentThumbMapper.selectList(commentThumbQueryWrapper);
            commentThumbList.forEach(commentThumb -> commentIdHasThumbMap.put(commentThumb.getCommentId(), true));
           }
        // 封装评论数量
        QueryWrapper<Comment> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("replyFatherId","count(*) as commentNum")
                .in("replyFatherId", commentIdSet)
                .last("group by replyFatherId");
        List<Map<String, Object>> maps = this.listMaps(queryWrapper);
        Map<Long, Integer> commentNumMap = new HashMap<>();
        maps.forEach(map -> {
            Long id = Long.valueOf(map.get("replyFatherId").toString());
            Integer commentNum = Integer.valueOf(map.get("commentNum").toString());
            commentNumMap.put(id, commentNum);
        });
        // 填充信息
        List<CommentVO> commentVOList = commentList.stream().map(comment -> {
            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(comment,commentVO);
            commentVO.setHasThumb(commentIdHasThumbMap.getOrDefault(comment.getId(), false));
            commentVO.setCommentNum(commentNumMap.getOrDefault(comment.getId(), 0));
            return commentVO;
        }).collect(Collectors.toList());
        commentVOPage.setRecords(commentVOList);
        return commentVOPage;
    }

    @Override
    public List<CommentVO> getByCommentIdList(Long replyId,HttpServletRequest request) {
        QueryWrapper<Comment> commentQueryWrapper = new QueryWrapper<>();
        //查询出有回复评论下的评论
        commentQueryWrapper.eq("replyFatherId",replyId);
        List<Comment> commentList = this.list(commentQueryWrapper);
        if(commentList==null || commentList.isEmpty()){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR,"评论为空");
        }
        // 2. 已登录，获取用户点赞状态
        Map<Long, Boolean> commentIdHasThumbMap = new HashMap<>();
        User loginUser = userService.getLoginUserPermitNull(request);
        if (loginUser != null) {
            Set<Long> commentIdSet = commentList.stream().map(Comment::getId).collect(Collectors.toSet());
            loginUser = userService.getLoginUser(request);
            // 获取点赞
            QueryWrapper<CommentThumb> commentThumbQueryWrapper = new QueryWrapper<>();
            commentThumbQueryWrapper.in("commentId", commentIdSet);
            commentThumbQueryWrapper.eq("userId", loginUser.getId());
            List<CommentThumb> commentCommentThumbList = commentThumbMapper.selectList(commentThumbQueryWrapper);
            commentCommentThumbList.forEach(commentCommentThumb -> commentIdHasThumbMap.put(commentCommentThumb.getCommentId(), true));
        }
        // 填充信息
        List<CommentVO> commentVOList = commentList.stream().map(comment -> {
            CommentVO commentVO = new CommentVO();
            BeanUtils.copyProperties(comment,commentVO);
            commentVO.setHasThumb(commentIdHasThumbMap.getOrDefault(comment.getId(), false));
            return commentVO;
        }).collect(Collectors.toList());
        return commentVOList;
    }
}




